# encoding=utf-8

import androidhelper, sqlite3, sys

reload(sys)
sys.setdefaultencoding('utf8')

droid = androidhelper.Android()
cx = sqlite3.connect("/sdcard/test.db")

cu = cx.cursor()
cu.execute('''
CREATE TABLE IF NOT EXISTS txm(
  isbn VARCHAR(15) PRIMARY KEY,
  source VARCHAR(4),
  name VARCHAR(15),
  code VARCHAR(8),
  amount INT
)''')

cu.execute('''
CREATE TABLE IF NOT EXISTS wtxm(
  name VARCHAR(15) PRIMARY KEY,
  source VARCHAR(4),  
  code VARCHAR(8),
  amount INT
)''')


def prompt(message, text=''):
    return droid.dialogGetInput('请输入', message, text).result.encode('utf-8')


def get_amount(number='1'):
    droid.dialogCreateInput('请输入', '数量', number, 'number')
    droid.dialogSetPositiveButtonText('确认')
    droid.dialogShow()
    return droid.dialogGetResponse().result[u'value'].encode()


def confirm(message):
    droid.dialogCreateAlert('', message)
    droid.dialogSetPositiveButtonText('是')
    droid.dialogSetNegativeButtonText('否')
    droid.dialogShow()
    return droid.dialogGetResponse().result[u'which'] == u'positive'


hy = {'lt': '蓝天', 'tw': '腾威', 'sf': '双丰', 'tdl': '同得利', 'tf': '同丰',
      'kf': '康夫', 'gzz': '高州仔', 'hzl': '化州佬', 'dsc': '东山村', 'ls': '老师',
      'ck': '赤坎', 'mz': '麻章', 'xhy': '新海源', 'yf': '樱风', 'fd': '富达',
      'bw': '霸王', 'dl': '迪翎'}
ks = hy.keys()
ks.sort()
vs = map(lambda k: hy[k], ks)

s = '''
货源：%s
名称：%s
编号：%s
数量：%s

是否要编辑？
'''


def get_source():
    droid.dialogCreateAlert('请选择货源：', '')
    droid.dialogSetItems(vs)
    droid.dialogShow()
    return ks[droid.dialogGetResponse().result[u'item']]


def execute(sql, action):
    print sql
    cu.execute(sql)
    cx.commit()
    droid.makeToast(action + '成功')


source = get_source()


def main1():
    code = droid.scanBarcode()[1]
    print code
    if not code: return
    isbn = code[u'extras'][u'SCAN_RESULT']
    cu.execute("SELECT * FROM txm WHERE isbn='%s'" % isbn)
    r = cu.fetchall()

    if r:
        r = r[0]
        name = r[2].encode('utf-8')
        code = r[3].encode('utf-8')
        amount = r[4]
        if confirm(s % (hy[r[1].encode('utf-8')], name, code, amount)):
            name = prompt('名称', name)
            code = prompt('编号', code)
            amount = get_amount(str(amount))
            execute("UPDATE txm SET name='%s',code='%s',amount=%s WHERE isbn='%s'"
                    % (name, code, amount, isbn), '修改')
    else:
        execute("INSERT INTO txm VALUES('%s','%s','%s','%s',%s)" %
                (isbn, source, prompt('名称'), prompt('编号'), get_amount()), '添加')


def main2():
    name = prompt('名称')
    cu.execute("SELECT * FROM wtxm WHERE name='%s'" % name)
    r = cu.fetchall()
    if r:
        r = r[0]
        code = r[2].encode('utf-8')
        amount = r[3]
        if confirm(s % (hy[r[1].encode('utf-8')], name, code, amount)):
            code = prompt('编号', code)
            amount = get_amount(str(amount))
            execute("UPDATE wtxm SET code='%s',amount=%s WHERE name='%s'"
                    % (code, amount, name), '修改')
    else:
        execute("INSERT INTO wtxm VALUES('%s','%s','%s',%s)" %
                (name, source, prompt('编号'), get_amount()), '添加')


txm = confirm('是否有条形码？')


def main():
    global txm
    if txm:
        main1()
    else:
        main2()
    droid.dialogCreateAlert('', '是否继续？')
    droid.dialogSetPositiveButtonText('是')
    droid.dialogSetNeutralButtonText('转换')
    droid.dialogSetNegativeButtonText('否')
    droid.dialogShow()
    r = droid.dialogGetResponse().result[u'which']
    if r == u'negative': return
    if r == u'neutral': txm = not txm
    main()


main()

cx.close
